package thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 自旋锁
 * Created on 2020/6/18.
 */
public class SpinLockDemo {
    //原子引用线程
    AtomicReference<Thread> ar = new AtomicReference<>();

    public void myLock(){
        Thread thread = Thread.currentThread();
        while (!ar.compareAndSet(null, thread)) {//这里cas不成功,会一直循环

        }
        System.out.println(Thread.currentThread().getName() + "\t come in.........");

    }

    public void myUnLock(){
        Thread thread = Thread.currentThread();
        ar.compareAndSet(thread, null);
        System.out.println(Thread.currentThread().getName() + "\t unlock.....");
    }

    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();
        new Thread(()->{
            spinLockDemo.myLock();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLockDemo.myUnLock();
        },"aa").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            spinLockDemo.myLock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLockDemo.myUnLock();
        },"bb").start();
    }
}
